import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { fetchTimetable, updateTimetableEntry } from './timetableAPI';

export const getTimetable = createAsyncThunk(
    'timetable/getTimetable',
    async () => {
        const timetable = await fetchTimetable();
        return timetable;
    }
);

export const editTimetableEntry = createAsyncThunk(
    'timetable/editTimetableEntry',
    async ({ id, entry }) => {
        const updatedEntry = await updateTimetableEntry(id, entry);
        return updatedEntry;
    }
);

const timetableSlice = createSlice({
    name: 'timetable',
    initialState: {
        entries: [],
        status: 'idle',
        error: null
    },
    reducers: {
        updateEntry: (state, action) => {
            const index = state.entries.findIndex(entry => entry.id === action.payload.id);
            if (index >= 0) {
                state.entries[index] = action.payload;
            }
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(getTimetable.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(getTimetable.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.entries = action.payload;
            })
            .addCase(getTimetable.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.error.message;
            })
            .addCase(editTimetableEntry.fulfilled, (state, action) => {
                const index = state.entries.findIndex(entry => entry.id === action.payload.id);
                if (index >= 0) {
                    state.entries[index] = action.payload;
                }
            });
    }
});

export const { updateEntry } = timetableSlice.actions;
export default timetableSlice.reducer;